package com.teemor.open.openauthspringbootstarter.gateway.filter;




import com.teemor.open.openauth.enums.ResultCode;
import com.teemor.open.openauth.validator.AuthValidator;
import com.teemor.open.openauth.validator.CheckBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/1/10
 */
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Autowired
    private AuthValidator authValidator;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            List<String> tokens = request.getHeaders().get("AUTH");
            List<String> refreshTokens = request.getHeaders().get("REFRESH");
            exchange.getResponse().getHeaders().add("Access-Control-Expose-Headers","validCode");


            CheckBean checkBean = new CheckBean(request.getPath().value(),
                    CollectionUtils.isEmpty(tokens) ? null : tokens.get(0),
                    CollectionUtils.isEmpty(refreshTokens) ? null : refreshTokens.get(0));
            ResultCode resultCode = authValidator.valid(checkBean);

            if (resultCode.equals(ResultCode.SUCCESS)) {
                exchange.getResponse().getHeaders().add("validCode", ResultCode.SUCCESS.value().toString());
                return chain.filter(exchange.mutate().request(request).build());
            }

            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            exchange.getResponse().getHeaders().add("validCode", resultCode.value().toString());
            return exchange.getResponse().setComplete();
        };
    }
}
